package com.jeanbart.service;

import com.jeanbart.bean.Player;
import com.jeanbart.util.AgetB;
import com.jeanbart.util.WowsFutureTask;
import com.jeanbart.util.ReadReplyFile;
import com.jeanbart.util.WowsHttpRequest;
import lombok.SneakyThrows;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;

public class ClientService {
    private JSONObject sendJSON;
    private JSONObject responseJSON;
    private boolean servcieState;
    public AgetB agetB = new AgetB();
    public ClientService(JSONObject sendJSON,boolean serviceState){
        this.sendJSON = sendJSON;
        this.servcieState = serviceState;
    }

    public List<List<Player>> SearchResult(){
        /*if(this.servcieState){
            SearchFromService(this.sendJSON);
        }else{*/
            SearchBySelf(this.sendJSON);
        //}
        return agetB.responseToList(this.responseJSON);
    }

    public void SearchFromService(JSONObject sendJSON){
        /*String requestUrl = "http://106.12.129.176:4396/getWinRate";
        String string = new WowsHttpRequest().JSONhttpRequest(requestUrl,sendJSON);
        this.responseJSON = JSONObject.fromObject(string);*/
    }

    public void SearchBySelf(JSONObject sendJson){
        String service  = sendJson.getString("service");
        List<Player> list = agetB.JSONGetListPlayer(sendJson.toString());
        UidInfo(list,service);
        //RateInfo(list,service);//没UID信息的时候会自动查总胜率信息，所以这句要注释掉，免得重复查询
        ShipRateInfo(list,service);
        List<Player> Teammate = new ArrayList<Player>();
        List<Player> Enemy = new ArrayList<Player>();
        for(int i =0 ; i<list.size();i++){
            if(list.get(i).getTeam()==1||list.get(i).getTeam()==0){
                Teammate.add(list.get(i));
            }else{
                Enemy.add(list.get(i));
            }
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("teammate", JSONArray.fromObject(Teammate));
        jsonObject.put("enemy",JSONArray.fromObject(Enemy));
        jsonObject.put("service",service);
        this.responseJSON = jsonObject;
    }

    @SneakyThrows
    public void UidInfo(List<Player> playerList, String service){
        File file = new File(System.getProperty("user.dir")).getParentFile();
        file = new File(file.toString() + "/shipName.json");
        if(!file.exists()){
            try {
                if(!file.getParentFile().exists()){
                    file.getParentFile().mkdirs();
                }
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
            getShipName();
        }
        JSONObject JSONShipNames = JSONObject.fromObject(new AgetB().readToString(file));
        for(int i =0 ;i<playerList.size();i++){
            playerList.get(i).setStep(1);
            String name = "";
            try{
                name = JSONShipNames.getString(playerList.get(i).getShipId());
            }catch(Exception e){};
            //获取船名，没有获取到就更新船名信息
            if(name==null||name==""){
                playerList.get(i).setShipName("未找到，可删掉shipName.json文件再试");
            }else{
                playerList.get(i).setShipName(name);
            }
        }
        //因为WG接口返回的中文船名和谐跟360的一致，所以需要额外加一个反和谐船名文件
        file = new File(file.getParent()+"/文化自信.json");
        if(file.exists()){
            JSONShipNames = JSONObject.fromObject(new String(new AgetB().readToString(file).getBytes(),"UTF-8"));
            for(int i =0 ;i<playerList.size();i++){
                String antiMosaicName = "";
                try{
                    antiMosaicName = JSONShipNames.getString(playerList.get(i).getShipId());
                }catch (Exception e){}
                //获取船名，没有获取到就更新船名信息
                if(antiMosaicName!=""){
                    playerList.get(i).setShipName(antiMosaicName);
                }
            }
        }
        new WowsFutureTask(playerList, service ,1).getResult();
    }
    public void RateInfo(List<Player> playerList,String service){
        for (int i = 0;i<playerList.size();i++){
            playerList.get(i).setStep(2);
        }
        new WowsFutureTask(playerList, service,2).getResult();
    }
    public void ShipRateInfo(List<Player> playerList,String service){
        for (int i = 0;i<playerList.size();i++){
            playerList.get(i).setStep(3);
        }
        new WowsFutureTask(playerList, service,3).getResult();
    }
    public void getShipName(){
        //接口地址
        String requestUrl="https://api.worldofwarships.asia/wows/encyclopedia/ships/";
        //params用于存储要请求的参数
        Map params = new HashMap();
        //showapi_appid的值，把###替换成你的appid
        params.put("application_id","32fdce021b11974b78343f010b2795d4");
        //我们请求的字符串
        params.put("fields","ship_id,name");
        params.put("language","zh-cn");
        params.put("page_no",1);
        //数字签名，###填你的数字签名，可以在你的个人中心看到
        //params.put("showapi_sign","###");
        //调用httpRequest方法，这个方法主要用于请求地址，并加上请求参数
        String string = new WowsHttpRequest().httpRequest(requestUrl,params);
        //处理返回的JSON数据并返回,因为API限制页的大小只有100，所以要自己合并
        JSONObject allPageData = new JSONObject();
        JSONObject jo= JSONObject.fromObject(string);
        int page_total = 0;
        if("ok".equals(jo.getString("status"))){
            page_total = (Integer) jo.getJSONObject("meta").get("page_total");
        }
        for(int i=1;i<=page_total;i++){
            if(i!=1){
                params.put("page_no",i);
                string = new WowsHttpRequest().httpRequest(requestUrl,params);
                jo= JSONObject.fromObject(string);
            }
            jo = jo.getJSONObject("data");
            Set set = jo.entrySet();
            Iterator iterator =set.iterator();
            while(iterator.hasNext()){
                jo = JSONObject.fromObject(iterator.next()).getJSONObject("value");
                String name = jo.getString("name");
                String shipId = jo.getString("ship_id");
                allPageData.put(shipId,name);
            }
        }
        WriteStringToFile(new File(System.getProperty("user.dir")).getParent()+"/shipName.json",allPageData.toString());
    }
    public void WriteStringToFile(String filePath,String s) {
        try {
            FileOutputStream fos = new FileOutputStream(filePath);
            fos.write(s.getBytes());
            fos.close();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
